# coding=utf-8

import sys
import time
import datetime

from builtins import int

sys.path.append("..")
from common.mysql.connect import MysqlConnector
from common.redis.connect import RedisConnector
from common.utils.time import get_yesterday_date
from common.utils.time import turn_date_to_ts
from models.manager import get_dict_of_mid_and_bid
from logic.cus_logic import CustomerLogic


def process_customer_buy_info(db, cus_id, date):
    """ 处理客户的购买信息
    """
    # 根据时间戳获取当天的开始和结束时间戳，作为基准
    ts_start = turn_date_to_ts(date)
    ts_end = ts_start + 60 * 60 * 24 - 1

    # 获取写数据的数据库连接实例
    mysql_db2 = MysqlConnector(2)

    # 判定客户是否已经有数据记录，没有需要新增，有的话只需要修改
    sql_if_exist = "select id from customer_grow_info where customer_id = %d" % cus_id
    if_exist = mysql_db2.select(sql_if_exist)
    if if_exist:
        exist = True
    else:
        exist = False

    sql_insert = "insert into customer_grow_info (`assistant_id`, `date`, `order_num`, `order_amount`,\
            `refund_order_num`, `refund_order_amount`) values "

    goods_sale_res = get_customer_buy_info(mysql, cus_id, ts_start, ts_end)
    if not goods_sale_res:
        # 当天没有售出，写入一条空值
        sql_insert += " (%d, %d, %d, %f, %d, %f) " % (assistant_id, ts_start, 0, 0.00, 0, 0.00)
    else:
        # 当天有售出，汇总售出结果
        sale_num_amount = cal_sale_num_amount(goods_sale_res)
        sql_insert += " (%d, %d, %d, %f, %d, %f) " % \
        (assistant_id, ts_start, sale_num_amount['sale_num'], sale_num_amount['sale_amount'], 0, 0.00)

    exec_res = mysql_db2.execute(sql_insert)
    if not exec_res:
        return False
    return True


if __name__ == '__main__':
    """ 计算客户当日下单，退款等信息，记录客户成长的关键性数据
    """
    # 获取要处理的日期
    if len(sys.argv) == 2:
        # 外部传递进来
        date = sys.argv[1]
    else :
        # 默认取前一天的日期
        date = datetime.datetime.strftime(get_yesterday_date(), "%Y-%m-%d")

    redis_14 = RedisConnector(14)
    mysql_db = MysqlConnector()

    while True:
        time.sleep(0.1)
        customer_id_pop = redis_14.rpop('customer_id_list')
        redis_14.lpush('customer_id_list', customer_id_pop)

        if customer_id_pop and (not redis_14.sismember('cus_list_' + date, customer_id_pop)):
            res = process_customer_buy_info(mysql_db, int(customer_id_pop), date)
            if res:
                redis_14.sadd('cus_list_' + date, customer_id_pop)
        else :
            print(date + " no more data")
            break
